/*
 * ******************************************************************************
 *   Copyright (c) 2013-2014 Gabriele Mariotti.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *  *****************************************************************************
 */

package it.gmariotti.cardslib.library.view.component;


import it.gmariotti.cardslib.library.ResourceTable;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.internal.MenuItem;
import it.gmariotti.cardslib.library.utils.DpUtils;
import it.gmariotti.cardslib.library.view.base.CardViewInterface;
import it.gmariotti.cardslib.library.view.helper.CardViewHelper;
import it.gmariotti.cardslib.library.view.helper.CardViewHelperUtil;
import ohos.agp.components.*;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;

import java.util.ArrayList;

/**
 * Compound View for Header Component.
 * It is built with base_header_layout xml file.
 * </p>
 * The base layout has two elements:
 * <ul>
 * <li><i>card_header_inner_frame</i>: frame which contains custom content.</li>
 * <li><i>card_header_button_frame</i>: frame which contains button.</li>
 * </ul>
 * </p>
 * You can populate and customize this layout using your CardHeader class.
 * See {@link CardHeader} for more info.
 * </p>
 * <b>You can use a custom layout for Header Component in your xml layout.</b>
 * </p>
 *
 * @author Gabriele Mariotti (gabri.mariotti@gmail.com)
 */
public class CardHeaderView extends StackLayout implements CardViewInterface {

    //--------------------------------------------------------------------------
    // Custom Layout
    //--------------------------------------------------------------------------
    /**
     * Header Layout
     */
    protected int card_header_layout_resourceID = ResourceTable.Layout_base_header_layout;

    //--------------------------------------------------------------------------
    // View
    //--------------------------------------------------------------------------
    /**
     * Compound View for this Component
     */
    protected Component mInternalOuterView;

    /**
     * Inner View.
     */
    protected Component mInternalInnerView;

    //--------------------------------------------------------------------------
    // Frame
    //--------------------------------------------------------------------------
    /**
     * InnerContent Frame
     */
    protected ComponentContainer mFrameInner;

    /**
     * Button Frame
     */
    protected ComponentContainer mFrameButton;

    //--------------------------------------------------------------------------
    // Button
    //--------------------------------------------------------------------------
    /**
     * Overflow
     */
    protected Image mImageButtonOverflow;

    /**
     * Expand/Collapse button
     */
    protected Image mImageButtonExpand;

    /**
     * Other Button
     */
    protected Image mImageButtonOther;

    /**
     * Card Model *
     */
    protected CardHeader mCardHeader;

    /**
     * Listener invoked when expand/collapse button is clicked
     */
    //protected OnClickListener mOnClickExpandCollapseActionListener;

    /**
     * Used to recycle ui elements.
     */
    protected boolean mIsRecycle = false;

    /**
     * Used to replace inner layout elements.
     */
    protected boolean mForceReplaceInnerLayout = false;

    /**
     * Popup Menu for overflow button
     */
    protected PopupDialog mPopupMenu;

    protected CardViewHelper mHelperImpl;
    private ArrayList<String> dynamicText;


    //--------------------------------------------------------------------------
    // Constructors
    //--------------------------------------------------------------------------

    public CardHeaderView(Context context) {
        this(context, null, "0");
    }

    public CardHeaderView(Context context, AttrSet attrs) {
        this(context, attrs, "0");
    }

    public CardHeaderView(Context context, AttrSet attrs, String defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
        dynamicText = new ArrayList<>();
        mHelperImpl = CardViewHelperUtil.getInstance(context);
    }

    //--------------------------------------------------------------------------
    // Init
    //--------------------------------------------------------------------------

    /**
     * Initializes component
     *
     * @param attrs
     * @param defStyle
     */
    protected void init(AttrSet attrs, String defStyle) {
        //Init attrs
        initAttrs(attrs, defStyle);

        //Init View
        initView();
    }

    /**
     * Init custom attrs.
     *
     * @param attrs
     * @param defStyle
     */
    protected void initAttrs(AttrSet attrs, String defStyle) {
        if (attrs.getAttr("card_header_layout_resourceID").isPresent()) {
            card_header_layout_resourceID = attrs.getAttr("card_header_layout_resourceID").get().getIntegerValue();
        }
    }

    /**
     * Inits view
     */
    protected void initView() {

        //Inflate the root view (outerView)
        LayoutScatter inflater = LayoutScatter.getInstance(mContext);
        mInternalOuterView = inflater.parse(card_header_layout_resourceID, this, true);

        //Get buttons from layout
        mImageButtonExpand = (Image) findComponentById(ResourceTable.Id_card_header_button_expand);
        mImageButtonOverflow = (Image) findComponentById(ResourceTable.Id_card_header_button_overflow);
        mImageButtonOther = (Image) findComponentById(ResourceTable.Id_card_header_button_other);

        //Get frames
        mFrameInner = (StackLayout) findComponentById(ResourceTable.Id_card_header_inner_frame);
        mFrameButton = (StackLayout) findComponentById(ResourceTable.Id_card_header_button_frame);

    }

    @Override
    public Component getInternalOuterView() {
        return mInternalOuterView;
    }

    /**
     * Adds a {@link CardHeader}.
     * <b>It is important to set all header values before launch this method</b>
     *
     * @param cardHeader CardHeader model
     */
    public void addCardHeader(CardHeader cardHeader) {
        //Set header
        mCardHeader = cardHeader;
        //build ui
        buildUI();
    }

    /**
     * This method builds UI.
     * If you are using standard base layout it sets up buttons and innerView.
     * If you are using your custom layout it sets your elements.
     */
    protected void buildUI() {
        if (mCardHeader == null) return;

        //Set button visibility


        setupButtons();

        //Setup InnerView
        setupInnerView();
    }

    /**
     * Sets Buttons visibility
     */
    @SuppressWarnings("deprecation")
    protected void setupButtons() {

        if (mCardHeader.isButtonOverflowVisible()) {
            visibilityButtonHelper(VISIBLE, HIDE, HIDE);

            addPopup();
            if (mPopupMenu == null && mCardHeader.getCustomOverflowAnimation() != null) {
                addCustomOverflowAnimation();
            }

        } else {

            if (mCardHeader.isButtonExpandVisible()) {
                visibilityButtonHelper(HIDE, VISIBLE, HIDE);
            } else {

                if (mCardHeader.isOtherButtonVisible() && mImageButtonOther != null) {
                    visibilityButtonHelper(HIDE, HIDE, VISIBLE);
                    //Check if button is not null
                    if (mImageButtonOther != null) {
                        if (mCardHeader.getOtherButtonDrawable() > 0) {
                            mHelperImpl.setButtonBackground(mImageButtonOther, mCardHeader.getOtherButtonDrawable());
                        }
                        addOtherListener();
                    }
                } else {
                    visibilityButtonHelper(HIDE, HIDE, HIDE);
                }
            }
        }
    }

    /**
     * Add Custom Overflow Animation
     */
    private void addCustomOverflowAnimation() {

        final CardHeader.CustomOverflowAnimation animation = mCardHeader.getCustomOverflowAnimation();
        if (animation != null && mImageButtonOverflow != null) {

            //Add a PopupMenu and its listener
            mImageButtonOverflow.setClickedListener(component -> animation.doAnimation(mCardHeader.getParentCard(), component));

        } else {
            if (mImageButtonOverflow != null)
                mImageButtonOverflow.setVisibility(HIDE);
        }

    }

    /**
     * Sets listener for OtherButtonAction
     */
    protected void addOtherListener() {

        if (mCardHeader.getOtherButtonClickListener() != null) {
            if (mImageButtonOther != null) {
                mImageButtonOther.setClickedListener(component -> {
                    if (mCardHeader.getOtherButtonClickListener() != null)
                        mCardHeader.getOtherButtonClickListener().onButtonItemClick(mCardHeader.getParentCard(), component);
                });
            }
        } else {
            if (mImageButtonOther != null) {
                mImageButtonOther.setClickable(false);
            }
        }
    }

    /**
     * Sets the inner view.
     */
    protected void setupInnerView() {
        if (mFrameInner != null) {
            //Check if view can be recycled
            //It can happen in a listView to improve performances or while refreshing a card
            if (!isRecycle() || isForceReplaceInnerLayout()) {

                if (isForceReplaceInnerLayout() && mFrameInner != null && mInternalInnerView != null)
                    mFrameInner.removeComponent(mInternalInnerView);

                //Inflate inner view
                mInternalInnerView = mCardHeader.getInnerView(getContext(), mFrameInner);
            } else {
                //View can be recycled.
                //Only setup Inner Elements
                if (mCardHeader.getInnerLayout() > -1)
                    mCardHeader.setupInnerViewElements(mFrameInner, mInternalInnerView);
            }
        }
    }


    /**
     * Helper method to setup buttons visibility
     *
     * @param overflowButtonVisibility <code>VISIBLE</code> to make visibile this button , otherwise <code>GONE</code>
     * @param expandButtonVisibility   <code>VISIBLE</code> to make visibile this button , otherwise <code>GONE</code>
     * @param otherButtonVisibility    <code>VISIBLE</code> to make visibile this button , otherwise <code>GONE</code>
     */
    protected void visibilityButtonHelper(int overflowButtonVisibility, int expandButtonVisibility, int otherButtonVisibility) {

        if (overflowButtonVisibility == VISIBLE || overflowButtonVisibility == HIDE) {
            if (mImageButtonOverflow != null) {
                mImageButtonOverflow.setVisibility(overflowButtonVisibility);
            }
        }
        if (expandButtonVisibility == VISIBLE || expandButtonVisibility == HIDE) {
            if (mImageButtonExpand != null) {
                mImageButtonExpand.setVisibility(expandButtonVisibility);
            }
        }
        if (otherButtonVisibility == VISIBLE || otherButtonVisibility == HIDE) {
            if (mImageButtonOther != null) {
                mImageButtonOther.setVisibility(otherButtonVisibility);
            }
        }
    }

    /**
     * Adds Popup menu
     */
    protected void addPopup() {

        //To prevent recycle
        mPopupMenu = null;

        if (mImageButtonOverflow != null) {

            // allow dynamic customization on popup menu
            boolean prepareMenu = mCardHeader.getPopupMenu() > CardHeader.NO_POPUP_MENU ? true : false;
            if (mCardHeader.getPopupMenuPrepareListener() != null) {
                //Dynamic customization
                prepareMenu = mCardHeader.getPopupMenuPrepareListener().onPreparePopupMenu(mCardHeader.getParentCard(), this);

            }

            if (prepareMenu) {
                //Add a PopupMenu and its listener
                mImageButtonOverflow.setClickedListener(component -> {
                    //It is null if the PopupMenuPrepareListener is null
                    //PopupMenu is built inside onClick() method to avoid building the menu when it is not necessary
                    mPopupMenu = _buildPopupMenu();
                    mPopupMenu.show();
                    mImageButtonOverflow.setSelected(true);
                });
            } else {
                if (mCardHeader.getCustomOverflowAnimation() == null) {
                    mImageButtonOverflow.setVisibility(HIDE);
                }
            }

        } else {
            if (mImageButtonOverflow != null)
                mImageButtonOverflow.setVisibility(HIDE);
        }
    }


    /**
     * Build the menu
     *
     * @return PopupDialog
     */
    private PopupDialog _buildPopupMenu() {
        OverflowDialog popup = new OverflowDialog(getContext(), mImageButtonOverflow);
        ComponentContainer rootLayout = createRootLayout();
        addDynamic(rootLayout);
        popup.setCustomComponent(rootLayout);
        popup.setOnDismissListener(() ->
                {
                    if (mImageButtonOverflow != null)
                        mImageButtonOverflow.setSelected(false);
                }
        );

        popup.setDialogListener(() -> {
            mPopupMenu.destroy();
            return true;
        });


        return popup;
    }

    /**
     * create RootLayout
     *
     * @return ComponentContainer
     */
    private ComponentContainer createRootLayout() {
        ComponentContainer rootLayout;
        if (mCardHeader.getPopupMenu() > CardHeader.NO_POPUP_MENU) {
            rootLayout = (ComponentContainer) LayoutScatter.getInstance(mContext).parse(mCardHeader.getPopupMenu(), null, false);
            Text text1 = (Text) rootLayout.findComponentById(ResourceTable.Id_menu_item1);
            if (text1 != null) {
                text1.setClickedListener(component -> {
                    MenuItem item = new MenuItem();
                    item.setTitle(text1.getText());
                    mCardHeader.getParentCard().setId(String.valueOf(ResourceTable.Id_menu_item1));
                    mCardHeader.getPopupMenuListener().onMenuItemClick(mCardHeader.getParentCard(), item);
                    mPopupMenu.destroy();
                });
            }

            Text text2 = (Text) rootLayout.findComponentById(ResourceTable.Id_menu_item2);
            if (text2 != null) {
                text2.setClickedListener(component -> {
                    MenuItem item = new MenuItem();
                    item.setTitle(text2.getText());
                    mCardHeader.getParentCard().setId(String.valueOf(ResourceTable.Id_menu_item2));
                    mCardHeader.getPopupMenuListener().onMenuItemClick(mCardHeader.getParentCard(), item);
                    mPopupMenu.destroy();
                });
            }

            Text text3 = (Text) rootLayout.findComponentById(ResourceTable.Id_menu_item3);
            if (text3 != null) {
                text3.setClickedListener(component -> {
                    MenuItem item = new MenuItem();
                    item.setTitle(text3.getText());
                    mCardHeader.getParentCard().setId(String.valueOf(ResourceTable.Id_menu_item3));
                    mCardHeader.getPopupMenuListener().onMenuItemClick(mCardHeader.getParentCard(), item);
                    mPopupMenu.destroy();
                });
            }

        } else {
            rootLayout = new DirectionalLayout(getContext());
            rootLayout.setLayoutConfig(new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT));
        }
        return rootLayout;
    }

    /**
     * rootLayout add Dynamic Component
     *
     * @param rootLayout
     */
    private void addDynamic(ComponentContainer rootLayout) {
        for (int i = 0; i < dynamicText.size(); i++) {
            String str = dynamicText.get(i);
            Text text = new Text(getContext());
            text.setLayoutConfig(new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_CONTENT, ComponentContainer.LayoutConfig.MATCH_CONTENT));
            text.setText(str);
            text.setTextSize(DpUtils.sp2px(getContext(), 18));
            text.setMarginBottom(10);
            text.setMarginTop(10);
            text.setMarginLeft(10);
            text.setMarginRight(10);
            text.setTextAlignment(TextAlignment.CENTER);
            text.setClickedListener(component -> {
                MenuItem item = new MenuItem();
                item.setTitle(str);
                mCardHeader.getPopupMenuListener().onMenuItemClick(mCardHeader.getParentCard(), item);
                mPopupMenu.destroy();
            });
            rootLayout.addComponent(text);
        }
    }

    public class OverflowDialog extends PopupDialog {
        private OnDismissListener onDismissListener;

        public OverflowDialog(Context context, Component contentComponent) {
            super(context, contentComponent);
        }


        @Override
        protected void onDestroy() {
            super.onDestroy();
            onDismissListener.onDismiss();
        }

        void setOnDismissListener(OnDismissListener onDismissListener) {
            this.onDismissListener = onDismissListener;
        }
    }


    public interface OnDismissListener {
        void onDismiss();
    }

    //--------------------------------------------------------------------------
    // Getters and Setters
    //--------------------------------------------------------------------------

    /**
     * Returns Listener invoked when expand/collpse button is clicked
     *
     * @deprecated
     * @return listener
     */
    /*public OnClickListener getOnClickExpandCollapseActionListener() {
        return mOnClickExpandCollapseActionListener;
    }*/

    /**
     * Attaches Listener to expand/collapse button
     *
     * @deprecated
     * @param onClickExpandCollapseActionListener listener
     */
    /*public void setOnClickExpandCollapseActionListener(OnClickListener onClickExpandCollapseActionListener) {
        this.mOnClickExpandCollapseActionListener = onClickExpandCollapseActionListener;

    }*/

    /**
     * Indicates if view can recycle ui elements.
     *
     * @return <code>true</code> if views can recycle ui elements
     */
    public boolean isRecycle() {
        return mIsRecycle;
    }

    /**
     * Sets if view can recycle ui elements
     *
     * @param isRecycle <code>true</code> to recycle
     */
    public void setRecycle(boolean isRecycle) {
        this.mIsRecycle = isRecycle;
    }

    /**
     * Indicates if inner layout have to be replaced
     *
     * @return <code>true</code> if inner layout can be recycled
     */
    public boolean isForceReplaceInnerLayout() {
        return mForceReplaceInnerLayout;
    }

    /**
     * Sets if inner layout have to be replaced
     *
     * @param forceReplaceInnerLayout <code>true</code> to recycle
     */
    public void setForceReplaceInnerLayout(boolean forceReplaceInnerLayout) {
        this.mForceReplaceInnerLayout = forceReplaceInnerLayout;
    }

    /**
     * Returns the {@link Image} used for overflow menu
     *
     * @return {@link Image}
     */
    public Image getImageButtonOverflow() {
        return mImageButtonOverflow;
    }

    /**
     * Returns the {@link Image} used for expand/collapse
     *
     * @return {@link Image}
     */
    public Image getImageButtonExpand() {
        return mImageButtonExpand;
    }

    /*
     *Returns the {@link ImageButton} used for other Button
     *
     * @return {@link ImageButton}
     */
    public Image getImageButtonOther() {
        return mImageButtonOther;
    }

    /**
     * Returns the Frame which contains the buttons
     *
     * @return ComponentContainer
     */
    public ComponentContainer getFrameButton() {
        return mFrameButton;
    }


    public void addMenuItem(String dynamic_item) {
        dynamicText.add(dynamic_item);
    }

}
